import { CCString } from 'cc';
import { error } from 'cc';
import { warn } from 'cc';
import { RichText } from 'cc';
import { Label } from 'cc';
import { _decorator, Component, Node } from 'cc';
import { EDITOR } from 'cc/env';
import Cfgs from '../configs/Cfgs';
import { LANTYPE } from '../configs/CfgLanguage';
const { ccclass, property } = _decorator;

@ccclass('MultiLabel')
export class MultiLabel extends Component {
    @property({ serializable: true })
    private _dataID: string = ""
    @property({ type: CCString, serializable: true })
    get dataID(): string {
        return this._dataID || ""
    }
    set dataID(value: string) {
        this._dataID = value
        if (!EDITOR) {
            this._needUpdate = true
        }
    }

    private _needUpdate: boolean = false

    get string(): string {
        let _string = Cfgs.Language.getText(this._dataID, Cfgs.curentLanguage)
        if (!_string) {
            console.warn("[LanguageLabel] 未找到语言标识,使用dataID替换")
            _string = this._dataID
        }
        return _string
    }

    set language(lang: LANTYPE) {
        Cfgs.setLanguage(lang)
        this._needUpdate = true
    }

    start() {
        this._needUpdate = true
        if (!this.getComponent(Label) && !this.getComponent(RichText)) {
            error(this.node.name, this._dataID)
            return
        }
    }

    update() {
        if (this._needUpdate) {
            this.updateLabel()
            this._needUpdate = false;
        }
    }

    updateLabel() {
        if (!this._dataID) {
            return; // 如果 dataID 为空，直接返回
        }

        // 获取文本组件（Label 或 RichText）
        const textComponent = this.getComponent(Label) || this.getComponent(RichText);
        if (!textComponent) {
            warn("[LanguageLabel] 该节点没有 cc.Label 或 cc.RichText 组件");
            return;
        }

        // 设置文本内容
        textComponent.string = this.string;
        console.log("更新文本成功"+textComponent.string);
        console.log("更新文本成功"+this.string);
    }

}


